//
//  ACAudienceViewController+LiveDelegate.m
//  ACLiteAVUISDK
//
//  Created by 冯琰琰 on 2021/4/8.
//

#import "ACAudienceViewController+LiveDelegate.h"
#import <SVProgressHUD.h>
#import "ACMsgModel.h"

@implementation ACAudienceViewController (LiveDelegate)

#pragma mark - LiveRoom
- (void)loginWithRoomID:(NSString *)roomID callback:(Callback)callback{
    self.liveRoom = [TRTCLiveRoom shareInstance];
    self.liveRoom.delegate = self;
    self.liveID = roomID;
   
    [self requestLiveInfo];
    
    self.me = [[TRTCLiveUserInfo alloc] init];
    self.me.userId = [ACUserProfileManager shareInstance].userModel.user_id;
    self.me.userName = [ACUserProfileManager shareInstance].userModel.nickname;
    self.me.avatarURL = [ACUserProfileManager shareInstance].userModel.avatar;
    
    TRTCLiveRoomConfig *config = [[TRTCLiveRoomConfig alloc] init];
    config.useCDNFirst = NO;

    NSString *userSig = [[ACUserProfileManager shareInstance] getUserSig];
   
    dispatch_queue_t queue = dispatch_queue_create("liveRoom", 0);
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    dispatch_async(queue, ^{
        [self.liveRoom loginWithSdkAppID:ACSDKAPPID user:self.me userSig:userSig config:config callback:^(int code, NSString * _Nullable message) {
            if (code == 0) {
                dispatch_semaphore_signal(semaphore);
            }
        }];
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        [self.liveRoom enterRoomWithRoomID:[roomID intValue] isAudience:YES callback:^(int code, NSString * _Nullable message) {
            if (code == 0) {
                DDLogInfo(@"成功进入房间------%@",roomID);
            }
        }];
    });
}


#pragma mark - TRTCLiveRoomDelegate

-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onRoomInfoChange:(TRTCLiveRoomInfo *)info{
    
}
-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onAudienceEnter:(TRTCLiveUserInfo *)user{
    
}
-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onAudienceExit:(TRTCLiveUserInfo *)user{
    
}
-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onAnchorEnter:(NSString *)userID{
    //  普通观众 渲染 主播视频
    dispatch_async(dispatch_get_main_queue(), ^{
        if (userID == self.me.userId) {
            [trtcLiveRoom startCameraPreviewWithFrontCamera:YES view:self.remoteVideoView callback:^(int code, NSString * _Nullable message) {
                if (code == 0) {
                    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
                }
            }];
        }else{
            if ([userID startsWith:@"tic_push_user"]) {
                // 显示白板
                [self showWriteBoardViewWithuserID:userID];
            }else{
                if (![self.anchor.userId isEqualToString:@""]) {
                    [trtcLiveRoom stopRemoteView:self.anchor.userId];
                }
                self.anchor.userId = userID;
                 // 移除上一个的， 开始渲染现在的。
                [trtcLiveRoom startRemoteView:self.anchor.userId View:self.remoteVideoView];
            }
        }
    });
}
-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom StreamToAnchor:(TRTCLiveUserInfo *)user{
    if (![self.anchor.userId isEqualToString:@""]) {
        [trtcLiveRoom stopRemoteView:self.anchor.userId];
    }
    self.anchor = user;
     // 移除上一个的， 开始渲染现在的。
    [trtcLiveRoom startRemoteView:self.anchor.userId View:self.remoteVideoView];
}

-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onAnchorExit:(NSString *)userID{
    //  普通观众 移除 主播视频
    if ([userID startsWith:@"tic_push_user"]) {
        [self removeWriteBoardViewWithuserID:userID];
    }else{
        [trtcLiveRoom stopRemoteView:userID];
    }
}

- (void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onResponseJoinAnchor:(TRTCLiveUserInfo *)user agreed:(BOOL)agreed{
    [SVProgressHUD showSuccessWithStatus:@"你好，收到了主播的回复"];
    if (agreed) { // 开始推声音的流 此处需要修改
        [trtcLiveRoom JoinAnchorStartToPublish];
        [self resetSpeakerBtnStatusLinkMic];
    }else{
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的上麦请求被拒绝，如果想上麦请再次请求" preferredStyle:UIAlertControllerStyleAlert];
        @weakify(self)
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
           // 恢复按钮的状态为邀请中
            @strongify(self)
            [self resetSpeakerBtnStatus];
        }];
        [alertVC addAction:cancelAction];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
}

-(void)trtcLiveRoomOnKickoutJoinAnchor:(TRTCLiveRoom *)liveRoom{
    [SVProgressHUD showSuccessWithStatus:@"你好，收到了连麦观众被踢出的消息"];
    [self resetSpeakerBtnStatus];
}

-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom OnRequestInviteAnchor:(TRTCLiveUserInfo *)user timeout:(double)timeout{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"您被主持人邀请成为主讲人，可以分享内容给其他观众" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"拒绝" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [trtcLiveRoom respondInviteAnchor:self.liveModel.created_by agreed:NO callback:^(int code, NSString * _Nullable message) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showSuccessWithStatus:@"你好，我拒绝了成为主讲人的邀请哟"];
            });
        }];
    }];
    @weakify(self);
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"进入主讲" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 跳转页面
        [trtcLiveRoom respondInviteAnchor:self.liveModel.created_by agreed:YES callback:^(int code, NSString * _Nullable message) {
            [SVProgressHUD showSuccessWithStatus:@"你好，我同意了成为主讲人的邀请哟"];
            [self_weak_ enterInviteAnchor];
        }];
    }];
    [alertVC addAction:cancelAction];
    [alertVC addAction:sureAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onRecvRoomTextMsg:(NSString *)message fromUser:(TRTCLiveUserInfo *)user{
    ACMsgModel *msgModel = [[ACMsgModel alloc] init];
    msgModel.userName = user.userName;
    msgModel.userId = user.userId;
    msgModel.userHeadImageUrl = user.avatarURL;
    msgModel.userMsg = message;
    [self bulletNewMsg:msgModel];
}
-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onRecvRoomCustomMsgWithCommand:(NSString *)command message:(NSString *)message fromUser:(TRTCLiveUserInfo *)user{
    
}
-(void)trtcLiveRoomOnQuitRoomPK:(TRTCLiveRoom *)liveRoom{
    
}

-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onRoomDestroy:(NSString *)roomID{
    
}
-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onWarning:(NSInteger)code message:(NSString *)message{
    
}
- (void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onError:(NSInteger)code message:(NSString *)message{
    
}
-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom beKickoutUser:(TRTCLiveUserInfo *)user{
    [SVProgressHUD showInfoWithStatus:@"你被主持人踢出了直播间"];
    [self exitLiveRoom];
}
@end
